package com.holly.unit.db.mp.dboperator;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.holly.unit.db.api.DbOperatorApi;
import com.holly.unit.db.api.constants.DataBaseConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 数据库操作的实现
 *
 * @author holly
 * @date 2020/11/4 14:48
 */
@Service
@Slf4j
public class DbOperatorImpl implements DbOperatorApi {

    @Override
    public int selectCount(String sql, Object... args) {
        return SqlRunner.db().selectCount(sql, args);
    }

    @Override
    public Set<Long> findSubListByParentId(String tableName, String parentIdsFieldName, String keyFieldName, Long keyFieldValue) {

        // 组装sql
        String sqlTemplate = "select {} from {} where {} like '%[{}]%'";
        String sql = StrUtil.format(sqlTemplate, keyFieldName, tableName, parentIdsFieldName, keyFieldValue.toString());

        // 查询所有子级的id集合，结果不包含被查询的keyFieldValue
        List<Object> subIds = SqlRunner.db().selectObjs(sql);

        // 转为Set<Long>
        return subIds.stream().map(i -> Long.valueOf(i.toString())).collect(Collectors.toSet());
    }

    @Override
    public String getDatabaseType() {
        DataSource dataSource = SpringUtil.getBean(DataSource.class);
        String DB_TYPE = "";
        Connection connection =null;
        try {
            connection = dataSource.getConnection();
            DatabaseMetaData md = connection.getMetaData();
            String dbType = md.getDatabaseProductName().toLowerCase();
            if(dbType.indexOf("mysql")>=0) {
                DB_TYPE = DataBaseConstants.DB_TYPE_MYSQL;
            }else if(dbType.indexOf("oracle")>=0) {
                DB_TYPE = DataBaseConstants.DB_TYPE_ORACLE;
            }else if(dbType.indexOf("sqlserver")>=0||dbType.indexOf("sql server")>=0) {
                DB_TYPE = DataBaseConstants.DB_TYPE_SQLSERVER;
            }else if(dbType.indexOf("postgresql")>=0) {
                DB_TYPE = DataBaseConstants.DB_TYPE_POSTGRESQL;
            }else {
                throw new SQLException("数据库类型:["+dbType+"]不识别!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }finally {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return DB_TYPE;
    }
}
